#coding:utf-8
from twisted.words.xish import domish
from twisted.words.protocols.jabber.xmlstream import TimeoutError
from twisted.internet.task import LoopingCall
from twisted.internet import reactor

class HeartBeat(LoopingCall):
	def __init__(self,client,per=60):
		super(HeartBeat,self).__init__(self._heartBeat)
		import weakref
		self._period = per
		self._client = weakref.proxy(client)
		self.errs = 0
	def start(self):
		super(HeartBeat,self).start(self._period)
	def _heartBeat(self):
		print "HEART BEAT"
		iq = self._client.IQ("get",self._client.profile.FULL_JID,10)
		iq.addElement('ping', 'urn:xmpp:ping')
		defer = iq.send()
		@defer.addCallback
		def heartBeatResponse(element):
			self.__errs = 0
		@defer.addErrback
		def heartBeatError(err):
			if err.type == TimeoutError:
				self.errs+=1
				if self.errs > 5:
					reactor.callFromThread(self._client.disconnect,restart=True)
					self.errs = 0
